<template>
  <a-select
    style="width: 100%"
    :model-value="modelValue"
    :placeholder="item.placeholder || '请选择' + item.label"
    :disabled="item.disabled || false"
    :loading="item.loading || false"
    :allowClear="item.allowClear || true"
    :showSearch="item.showSearch || false"
    :filterOption="item.filterOption || false"
    :name="item.field"
    @change="handleChange"
    @focus="handleFocus"
    @blur="handleBlur"
  >
    <a-select-option
      v-for="option in options"
      :key="option.value"
      :value="option.value"
      >{{ option.label }}</a-select-option
    >
  </a-select>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { SelectProps } from "ant-design-vue/es/select";

interface Item {
  options?: SelectProps["options"];
  placeholder?: string;
  disabled?: boolean;
  loading?: boolean;
  allowClear?: boolean;
  showSearch?: boolean;
  dictCode?: string | number; 
  filterOption?: SelectProps["filterOption"];
}

interface Option {
  value: string | number;
  label: string | number;
}
// 接收属性和事件
const props = defineProps<{
  item: Item;
  modelValue: any;
}>();

// 定义组件事件
interface MySelectEmits {
  (e: "update:modelValue", value: string | number | (string | number)[]): void;
  (
    e: "change",
    value: string | number | (string | number)[],
    option: any
  ): void;
  (e: "focus"): void;
  (e: "blur"): void;
}

const emit = defineEmits<MySelectEmits>();

const options = ref<Option[]>([]);
// 内部选中值
const selectedValue = ref(props.modelValue);

// 监听外部 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    selectedValue.value = newVal;
  }
);

//监听是否存在字典码
watch(
  () => props.item.dictCode,
  (newVal) => {
    if (newVal && (!props.item.options || props.item.options.length === 0)) {
      //根据字典码调用字典接口
      options.value = [
        {
          label: '字典项1',
          value: '1'
        },
        {
          label: '字典项2',
          value: '2'
        }
      ]
    }else{
        options.value = (props.item.options || []).map(opt => ({
        label: opt.label,
        value: opt.value
      })) as Option[];
    }
    
  },
  { immediate: true }
);

// 处理选中值变化
const handleChange = (
  value: string | number | (string | number)[],
  option: any
) => {
  console.log(value, option);
  emit("update:modelValue", value);
  emit("change", value, option);
};

// 处理焦点事件
const handleFocus = () => {
  emit("focus");
};

// 处理失焦事件
const handleBlur = () => {
  emit("blur");
};
</script>

<style scoped></style>
